__author__ = 'drazen.popovic'

from SocketServer import ThreadingTCPServer, StreamRequestHandler, TCPServer
import logging
from config import ADDRESS,PORT,CURRENCY,AMOUNT
from Parser import *
from Transaction import *
import datetime

class RequestHandler(StreamRequestHandler):
    def setup(self):
        print "logged"
        self.logger = logging.getLogger()
        StreamRequestHandler.setup(self)
    def handle(self):
        print "handling"
        self.logger.debug("Handling request from %s", self.client_address)
        trx = Transaction()
        try:
            self.logger.debug("Receiving CalcPriceReq")
            pduCalcPriceReq = PDUCalculatePriceReq()
            pduCalcPriceReq.readFromStream(self.rfile)
            intAppId = pduCalcPriceReq.hdr.getAppId()
            trx.setImsi(pduCalcPriceReq.body.getImsi())
            trx.setMsisdn(pduCalcPriceReq.body.getMsisdn())
            trx.setGkId(pduCalcPriceReq.body.getGkId())
            trx.setIptId(pduCalcPriceReq.body.getIptId())
            trx.setSmsDatetime(pduCalcPriceReq.body.getSmsDatetime())
        except Exception as e:
            self.logger.error("%s", e.message)
            return
        try:
            self.logger.debug("Sending CalPriceResp")
            pduCalcPriceResp = PDUCalculatePriceResp()
            pduCalcPriceResp.hdr.setAppId(intAppId)
            pduCalcPriceResp.body.setImsi(trx.getImsi())
            pduCalcPriceResp.body.setGkId(trx.getGkId())
            pduCalcPriceResp.body.setIptId(trx.getIptId())
            pduCalcPriceResp.body.setStatusCode(StatusCodeFromString("OK"))
            dtEnterence = datetime.datetime.now()
            pduCalcPriceResp.body.setEnterenceDatetime(dtEnterence)
            pduCalcPriceResp.body.setPayDatetime(dtEnterence)
            dtLeave = dtEnterence + datetime.timedelta(hours=1)
            pduCalcPriceResp.body.setLeaveDatetime(dtLeave)
            pduCalcPriceResp.body.setExitDatetime(dtLeave)
            pduCalcPriceResp.body.setAmount(AMOUNT)
            pduCalcPriceResp.body.setCurrency(CURRENCY)
            pduCalcPriceResp.body.setTimestamp(dtEnterence)
            pduCalcPriceResp.writeToStream(self.wfile)
            trx.setAmount(AMOUNT)
            trx.setCurrency(CURRENCY)
        except Exception as e:
            self.logger.error("%s", e.message)
            return
        try:
            self.logger.debug("Receiving TransactionStatus")
            pduTransactionStatus = PDUTransactionStatus()
            pduTransactionStatus.readFromStream(self.rfile)
            if pduTransactionStatus.body.getStatusCode() != StatusCodeFromString("OK"):
                self.logger.warning("Transaction Failed")
                return
            self.logger.debug("Transaction Succeded")
        except Exception as e:
            self.logger.error("%s", e.message)
            return
        try:
            self.logger.debug("Sending TransactionSuccess")
            pduTransactionSuccess = PDUTransactionSuccess()
            pduTransactionSuccess.body.setStatusCode(StatusCodeFromString("OK"))
            pduTransactionSuccess.body.setTimestamp(datetime.datetime.now())
            pduTransactionSuccess.writeToStream(self.wfile)
        except Exception as e:
            self.logger.error("%s", e.message)
            return
        self.logger.debug("Transaction created successfully: %s", str(trx))
        trx.save()
        return

if __name__ == "__main__":
    lstnr = ThreadingTCPServer((ADDRESS,PORT), RequestHandler)
    lstnr.serve_forever()